﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFromTools
{
    public partial class LogTypeForm : Form
    {

        #region Constants

        private const string LOG_TYPE_PATTERN = @"InsertActivity\(""(\w+)""";


        #endregion

        private List<String> logTypes;

        public LogTypeForm()
        {
            InitializeComponent();

            logTypes = new List<string>();
        }

        private void btnSelectOriginal_Click(object sender, EventArgs e)
        {
            if (folderDialog.ShowDialog() == DialogResult.OK)
            {
                txtOriginalPath.Text = folderDialog.SelectedPath;
            }
        }

        private void btnParseFiles_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(txtOriginalPath.Text) || txtOriginalPath.Text.Length < 4)
            {
                MessageBox.Show("请先选择项目所在目录");
            }
            else
            {
                ParseCSFiles(txtOriginalPath.Text, txtLogType);
                WriteLine(txtLogType, "处理完毕！ 结果如下：");

                string s = @"INSERT INTO `base_activity_log_type` (`SystemKeyword`,`Name`,`Enabled`,`Category`,`DisplayOrder`)
SELECT '{0}', '{0} Desc', 1, 'System', 20000 FROM DUAL
	WHERE NOT EXISTS(
	SELECT `Id` FROM  `base_activity_log_type`
	WHERE `SystemKeyword` = '{0}');";

                var sb = new StringBuilder("");
                foreach(var t in logTypes)
                {
                    sb.AppendLine(String.Format(s, t));
                }

                //txtLogType.AppendText(String.Join(Environment.NewLine, logTypes));
                txtLogType.AppendText(sb.ToString());

                MessageBox.Show("处理完毕!");
            }
        }

        #region Helper

        private static void WriteLine(TextBox txtBox, String text)
        {
            txtBox.Focus();
            txtBox.AppendText(text + Environment.NewLine);
            txtBox.ScrollToCaret();
            System.Windows.Forms.Application.DoEvents();
        }

        public static bool ContainString(string s, params string[] stringSet)
        {
            bool ret = false;
            foreach (string element in stringSet)
            {
                if (element.ToLower() == s.ToLower())
                {
                    ret = true;
                    break;
                }
            }

            return ret;
        }

        public static string GetFileExtension(string fileName)
        {
            int length = fileName.Length;
            int startIndex = length;
            while (--startIndex >= 0)
            {
                char ch = fileName[startIndex];
                if (ch == '.')
                {
                    return fileName.Substring(startIndex, length - startIndex);
                }
                if (((ch == Path.DirectorySeparatorChar) || (ch == Path.AltDirectorySeparatorChar)) || (ch == Path.VolumeSeparatorChar))
                {
                    break;
                }
            }
            return string.Empty;
        }

        private static string GetFirstMatch(string pattern, string originalText)
        {
            MatchCollection matches = GetMatches(pattern, originalText);
            if (matches.Count > 0)
            {
                return matches[0].Value;
            }
            else
            {
                return null;
            }
        }

        private static MatchCollection GetMatches(string pattern, string originalText)
        {
            Regex tmpRegex = new Regex(pattern, RegexOptions.IgnoreCase);
            MatchCollection matches = tmpRegex.Matches(originalText);

            return matches;
        }

        #endregion

        public void ParseCSFiles(string srcPath, TextBox txtBox)
        {
            string[] fileList = Directory.GetFileSystemEntries(srcPath);
            // 遍历所有的文件和目录
            foreach (string file in fileList)
            {
                // file可能为子目录，所以 先作为目录处理如果存在这个目录，就递归该目录下面的文件
                if (Directory.Exists(file))
                {
                    ParseCSFiles(file, txtBox);
                }
                else
                {
                    //string fileExtension = GetFileExtension(file);
                    //if (String.IsNullOrEmpty(fileExtension))
                    //    continue;
                    //if (!String.IsNullOrEmpty(fileExtension))
                    //{
                    //    if (!ContainString(fileExtension.ToLower(), ".cs"))
                    //    {
                    //        continue;
                    //    }
                    //}
                    if (!file.ToLower().EndsWith("controller.cs"))
                    {
                        continue;
                    }

                    try
                    {
                        ExtractLogType(file);
                    }
                    catch (Exception e)
                    {

                        MessageBox.Show(e.ToString());
                    }

                    //File.Copy(file, destPath + Path.GetFileName(file), true);
                    if (txtBox != null)
                    {
                        WriteLine(txtBox, file);
                    }
                }
            }
        }

        private void ExtractLogType(string filename)
        {
            var txt = System.IO.File.ReadAllText(filename);

            GetLogTypes(txt);
        }

        private void GetLogTypes(string text)
        {
            var matches = GetMatches(LOG_TYPE_PATTERN, text);
            foreach (var m in matches)
            {
                var match = m as Match;
                if (match != null)
                {
                    foreach (var g in match.Groups)
                    {
                        var t = g as Match;
                        if (t != null)
                            continue;
                        var group = g as Group;
                        //if (group != null && !group.Value.StartsWith("$") && tokens.Count(t => t.Key == group.Value) == 0)
                        //{
                        //    tokens.Add(new Token(group.Value, TOKEN_TEST_VALUE));
                        //}
                        if(!logTypes.Contains(group.Value))
                        {
                            logTypes.Add(group.Value);
                        }
                    }
                }
            }
        }
    }
}
